package com.xxtx.trade.agent.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.XmlUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xxtx.trade.agent.mapper.TradeSysAgentMapper;
import com.xxtx.trade.agent.service.AgentWxService;
import com.xxtx.trade.agent.vo.SignUtil;
import com.xxtx.trade.agent.vo.SysConfigEnums;
import com.xxtx.trade.agent.vo.WeChatConf;
import com.xxtx.trade.agent.vo.WeiChatUnifyOrderEntity;
import com.xxtx.trade.common.exception.BusinessException;
import com.xxtx.trade.common.util.cache.CacheManager;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import net.bytebuddy.implementation.bytecode.Throw;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import cn.hutool.http.HttpUtil;

@Service
public class AgentWxServiceImpl implements AgentWxService {
    private static final Logger LOGGER = LoggerFactory.getLogger(AgentWxServiceImpl.class);
    @Autowired
    private TradeSysAgentMapper tradeSysAgentMapper;
    //根据appi选择
    @Override
    public WxMpUser getWxUserInfosByAppid(String appid,String code) {
        //根据appid 来定位收款配置
        Map<String, Object> map = getSysConfigBYtitles(appid);
        Map<String, String> result = accessToken(code, appid, String.valueOf(map.get("appSecret")));
        if (result==null){
            throw new  BusinessException("授权失败，请重新登录再试");
        }
        //获取微信用户信息

        Map<String, String> resultUser = wxUserInfo(result.get("access_token"), result.get("openid"));
        WxMpUser user = new WxMpUser();
        user.setOpenId(resultUser.get("openid"));
        user.setNickname(resultUser.get("nickname"));
        user.setHeadImgUrl(resultUser.get("headimgurl"));
        return user;
    }

    @Override
    public Map<String, Object> getWxPayInfo(String id, Long price, String wchatOpenid, String wxAppId, String wxMchId, String wxKeySign,String returnUrl,String title) {
        WeiChatUnifyOrderEntity unifyOrder = new WeiChatUnifyOrderEntity();
        unifyOrder.setAppid(wxAppId);
        unifyOrder.setMch_id(wxMchId);
        unifyOrder.setNotify_url(returnUrl);//购买换卡邮费
//        if (1 == isTest.intValue()) {
//            unifyOrder.setTotal_fee(1);//分
//        } else {
        String s = String.valueOf(price);
        unifyOrder.setTotal_fee(Integer.valueOf(s));//分
//        }
        unifyOrder.setAttach(title);
        unifyOrder.setBody(title);
        unifyOrder.setOut_trade_no(id);
        unifyOrder.setTrade_type("JSAPI");
        unifyOrder.setOpenid(wchatOpenid);
        try {
            unifyOrder.setSpbill_create_ip(InetAddress.getLocalHost().getHostAddress());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        LOGGER.info("微信签名数据 {}", JSONObject.toJSONString(unifyOrder));
        unifyOrder.setSign(SignUtil.sign(unifyOrder, wxKeySign));
        String reqStr = unifyOrder.toXml();
        LOGGER.info("微信获取调起数据 {}", reqStr);
        String result = HttpUtil.post(WeChatConf.URL_UNIFY_ORDER, reqStr);
        LOGGER.info("获取微信激活订单返回报文：{}", result);
        Map<String, Object> map = XmlUtil.xmlToMap(result);
        if (!"OK".equals(map.get("return_msg"))) {
            throw new RuntimeException("获取微信支付订单失败");
        }
        Object prepayId = map.get("prepay_id");
        String nonceStr = RandomUtil.randomString(10);
        long timestamp = System.currentTimeMillis() / 1000;

        Map<String, Object> reMap3 = new HashMap<>();
        reMap3.put("appId", map.get("appid"));
        reMap3.put("timeStamp", String.valueOf(timestamp));
        reMap3.put("nonceStr", nonceStr);
        reMap3.put("package", "prepay_id=" + prepayId);
        reMap3.put("signType", "MD5");
        LOGGER.info("微信签名数据 {}", reMap3.toString());
        String sign = SignUtil.sign(reMap3, wxKeySign);
        reMap3.put("paySign", sign);
        Map<String, Object> reMap2 = new HashMap<>();
        reMap2.put("param", reMap3);
        reMap2.put("orderId", id);
        return reMap2;
    }

    @Override
    public Map<String, Object> getAgentCollect(String appid) {
        return getSysConfigBYtitles(appid);
    }


    @Autowired
    private CacheManager cacheManager;
    /**
     * 查询系统配置 缓存
     */
    public  Map<String,Object> getSysConfigBYtitles(String title){
        String text = (String) cacheManager.get(SysConfigEnums.REDIS_CONFIG + title);
        if (text==null){
            text=tradeSysAgentMapper.selectSysConfigBYTitls(title);
            if (text==null){
                throw   new BusinessException("查询不到当前收款配置");
            }else {
                cacheManager.set(SysConfigEnums.REDIS_CONFIG + title,text);
            }
        }
        return JSON.parseObject(text);
    }


    /**
     * 用户授权获取openId
     */
    public Map<String, String> accessToken(String code,String appid,String appSecret) {

        String oauth2_url = WeChatConf.ACCESS_TOKEN.replace("APPID", appid).replace("SECRET", appSecret).replace("CODE", code);
        LOGGER.info("微信获取openId路径 {}", oauth2_url);
        String result = HttpUtil.post(oauth2_url, "");
        LOGGER.info("获取openId返回报文：{}", result);
        Map<String, Object> jsonObject = (Map<String, Object>) JSONObject.parseObject(result);
        if (jsonObject.get("openid") == null) {
            LOGGER.info("获取openId失败");
            return null;
        }
        Map<String, String> ret = new HashMap<>();
        ret.put("openid", jsonObject.get("openid").toString());
        ret.put("access_token", jsonObject.get("access_token").toString());
        ret.put("expires_in", jsonObject.get("expires_in").toString());
        ret.put("refresh_token", jsonObject.get("refresh_token").toString());
        ret.put("scope", jsonObject.get("scope").toString());
        return ret;
    }

    /**
     * 获取微信用户头像和昵称
     */
    public Map<String, String> wxUserInfo(String accessToken, String openId) {
        String userInfoUrl = WeChatConf.USER_INFO.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        LOGGER.info("拉取用户信息url {}", userInfoUrl);
        String result = HttpUtil.post(userInfoUrl, "");
        LOGGER.info("拉取用户信息报文：{}", result);
        Map<String, Object> jsonObject = (Map<String, Object>) JSONObject.parseObject(result);
        if (jsonObject.get("nickname") == null) {
            LOGGER.info("拉取用户信息失败");
            return null;
        }
        Map<String, String> ret = new HashMap<>();
        ret.put("openid", jsonObject.get("openid").toString());
        ret.put("nickname", jsonObject.get("nickname").toString());
        ret.put("sex", jsonObject.get("sex").toString());
        ret.put("province", jsonObject.get("province").toString());
        ret.put("city", jsonObject.get("city").toString());
        ret.put("country", jsonObject.get("country").toString());
        ret.put("headimgurl", jsonObject.get("headimgurl").toString());
        ret.put("privilege", jsonObject.get("privilege").toString());
        //ret.put("unionid", jsonObject.get("unionid").toString());
        return ret;
    }


}
